package com.yidu.hbatsft.service.impl;

import com.github.pagehelper.PageHelper;
import com.yidu.hbatsft.dao.*;
import com.yidu.hbatsft.domain.*;

import com.yidu.hbatsft.service.AtsEmpAthleteService;
import com.yidu.privilege.Dao.UserAndroleMapper;
import com.yidu.privilege.Dao.UserDao;
import com.yidu.privilege.Domain.User;
import com.yidu.privilege.Domain.UserAndrole;
import com.yidu.utils.FileTools;
import com.yidu.utils.Page;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
@Service
public class AtsEmpAthleteImpl implements AtsEmpAthleteService {
    @Resource
    AtsEmpAthleteMapper mapper;
    //查询教练员所用到的
    @Resource
    AtsEmpCoachMapper coachMapper;
    //查询运动项目所用到的
    @Resource
    AtsBaseSportMapper sprotMapper;
    @Resource
    UserDao userDao;
    @Resource
    UserAndroleMapper userandroleMapper;
    @Resource
    AtsEmpAthleteVoMapper atsEmpAthleteVoMapper;
    //教练员和运动员表
    @Resource
    AtsEmpCoachAthleteMapper coachAthleteMapper;

    @Resource
    AtsDataDicMapper dataDicMapper;

    /**
     * 文件上传工具
     */
    @Resource
    FileTools fileTools;
    @Override
    public List<AtsEmpAthlete> findAll(Page page) {
        return mapper.findAll(page);
    }

    @Override
    public List<AtsEmpAthlete> findAllx() {
        return mapper.findAllx();
    }

    @Override
    public AtsEmpAthleteVo findByid(Integer id) {

        return atsEmpAthleteVoMapper.findByid(id);
    }

    @Override
    public List<AtsEmpAthlete> findAllX(Integer pageNum, Integer pageSize,String athleteName) {
        //开始处
        PageHelper.startPage(pageNum,pageSize);

        return mapper.findAllX(athleteName);
    }

    public int count(){
        return  mapper.findCount();
    }

    @Override
    public List<AtsEmpCoach> findAllCoach() {

        return coachMapper.findAll();
    }

    @Override
    public List<AtsBaseSport> findAllSport() {
        return sprotMapper.selAllSportNmae();
    }

    @Override
    public int upAthleteDate(AtsEmpAthleteVo ats,MultipartFile file) {
        //System.out.println("运动员所在项目:"+ats.getSportId()+"运动员文化:"+ats.getEducation());
        AtsEmpAthlete athlete = new AtsEmpAthlete();
        User user = new User();
        AtsEmpCoachAthlete coachAthlete = new AtsEmpCoachAthlete();
        if(ats.getOldCoach()==null || "".equals(ats.getOldCoach())){
            ats.setOldCoach("6");
        }else{
            athlete.setOldCoach(ats.getOldCoach());
        }
        System.out.println("==============元教练"+ats.getOldCoach());
        //设置运动员表的参数
        athlete.setAthleteName(ats.getAthleteName());//设置姓名
        athlete.setSportId(ats.getSportId());//设置所在项目ID
        athlete.setCoachId(ats.getCoachId());//设置教练ID
        athlete.setAddr(ats.getAddr());//设置地址
        athlete.setDeptName(ats.getDeptName());//设置部门名称
        athlete.setPostName(ats.getPostName());//设置岗位名称
        athlete.setPhone(ats.getPhone());//设置电话
        athlete.setPlay(ats.getPlay());//设置打法
        athlete.setAthleteExp(ats.getAthleteExp());//设置运动员说明
        athlete.setMentality(ats.getMentality());//设置心理说明
        athlete.setTechnical(ats.getTechnical());//设置技术特征
        athlete.setTactics(ats.getTactics());//设置战术特征
        athlete.setAthleteSex(ats.getAthleteSex());//设置运动员性别
        athlete.setBestResult(ats.getBestResult());//设置最好成绩
        athlete.setBirthday(ats.getBirthday());//设置生日
        athlete.setFamily(ats.getFamily());//设置家庭情况
        athlete.setOldCoach(ats.getOldCoach());//设置原教练
        athlete.setNativePlace(ats.getNativePlace());//设置籍贯
        athlete.setHand(ats.getHand());//设置习惯手
        athlete.setClub(ats.getClub());//设置俱乐部
        athlete.setTrainingYears(ats.getTrainingYears());//设置结束训练年限
        athlete.setJoinTime(ats.getJoinTime());//设置进队时间
        athlete.setGraduateSchool(ats.getGraduateSchool());//设置毕业学校
        athlete.setOrganName(ats.getOrganName());//注册单位
        athlete.setEducation(ats.getEducation());//设置文化程度
        athlete.setIsva(1);//设置为有效
        athlete.setLevel(ats.getLevel());//设置技术等级

        user.setUsEmail(ats.getUsEmail());//用户设置Email
        user.setUsName(ats.getUsName());//设置登陆用户名
        user.setUsPass(ats.getUsPass());//设置登陆用户密码
        user.setUsType("运动员");//设置用户类型
        user.setUsPhone(ats.getPhone());//设置用户联系方式
        user.setUsState("0");//设置状态为0

        //教练运动员关系表
        coachAthlete.setAthleteName(ats.getAthleteName());//设置运动员名字
        coachAthlete.setAthleteId(ats.getAthleteId());//设置运动员ID
        coachAthlete.setExp(ats.getAthleteExp());//设置运动员EXP
        coachAthlete.setCoachId(ats.getCoachId());//设置教练ID
        coachAthlete.setStartTime(ats.getJoinTime());//设置起始时间
        coachAthlete.setEndTime(ats.getTrainingYears());//设置结束时间
        coachAthlete.setIsva(1);//设置状态为1

        //判断文件非空时
        if (file.getOriginalFilename() != null && !"".equals(file.getOriginalFilename())) {
            //处理异常
            try {
                String usPhoto = fileTools.saveFile("UserImg", file);
                user.setUsPhoto(usPhoto);//设置头像
                System.err.println("===================" + usPhoto);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //如果ID不等于空则是修改
        //查询教练名称
        AtsEmpCoach coachinfo =  coachMapper.findById(ats.getCoachId());

        if(ats.getAthleteId() !=null){
            athlete.setAthleteId(ats.getAthleteId());
            user.setUsId(ats.getUsId());
            //System.out.println("=========================技术等级:"+ats.getLevel()+"战术:"+ats.getTactics()+"技术"+ats.getTechnical());
            //查询到修改前的数据
            AtsEmpAthlete loadingupdate = mapper.findByid(ats.getAthleteId());

            //System.err.println("=========获取"+user.getUsPhoto());
            System.out.println("==============="+coachinfo.getCoachName());
            coachAthlete.setCoachName(coachinfo.getCoachName());
            int cout = mapper.updateByPrimaryKeySelective(athlete);
            if(cout>0){
                //修改用户表
                int c = userDao.update(user);
                //查询到运动员教练关系表ID
               AtsEmpCoachAthlete e = coachAthleteMapper.findById(ats.getAthleteId(),loadingupdate.getCoachId());
                coachAthlete.setCaId(e.getCaId());
                //修改运动员教练关系表
                int t = coachAthleteMapper.updateByPrimaryKey(coachAthlete);
                if(c>0 && t>0){
                    return cout;
                }else{
                    System.err.println("教练表或用户表数据没有修改完成");
                    return 0;

                }
            }
        }else{
            //新增运动员表
            int insertCout = mapper.insert(athlete);
            if(insertCout>0){
                //新增用户表
                user.setUsWaiid(athlete.getAthleteId());

                int u = userDao.insert(user);

                if(u>0){
                    //新增运动员教练关系表
                    coachAthlete.setAthleteId(athlete.getAthleteId());
                    coachAthlete.setCoachName(coachinfo.getCoachName());
                    //新增用户与角色表

                    UserAndrole userAndrole = new UserAndrole();
                    userAndrole.setUsId(user.getUsId());
                    userAndrole.setRoId(21);
                     userandroleMapper.insert(userAndrole);
                    System.out.println("===============ur!"+athlete.getAthleteId());
                    int c = coachAthleteMapper.insert(coachAthlete);
                    if(c>0){
                        return insertCout;
                    }
                }
            }
        }
        return 0;
    }

    @Override
    public int deleteAthleteDate(Integer athleteId) {
        AtsEmpAthlete athleteInfo = mapper.findByid(athleteId);
        System.out.println("=================="+athleteId);
        AtsEmpCoachAthlete coachAthleteInfo = coachAthleteMapper.findById(athleteInfo.getAthleteId(),athleteInfo.getCoachId());


        int cout = coachAthleteMapper.deleteByPrimaryKey(coachAthleteInfo.getCaId());
        if(cout >0){
            userDao.deleteByAthleteId(athleteId);
            return mapper.deleteByPrimaryKey(athleteId);
        }else{
            return 0;
        }

    }

    @Override
    public List<AtsEmpCoachAthlete> coachAthelete(Integer id) {

        return coachAthleteMapper.coachAthelete(id);

    }

    @Override
    public List<AtsEmpAthlete> findbycoachId(Integer id) {
        return mapper.findbycoachId(id);
    }

    @Override
    public List<AtsEmpAthlete> findByName(String athleteName) {

        return mapper.findByName(athleteName);
    }

    /**
     * 查询运动员列表  不带分页
     * @param atsEmpAthlete
     * @return
     */
    @Override
    public List<AtsEmpAthlete> findAllLX(AtsEmpAthlete atsEmpAthlete) {
        return mapper.findAllLX(atsEmpAthlete);
    }

    /**
     * 根据科研教练查询运动员
     * @param oldCoachId
     * @return
     */
    @Override
    public List<AtsEmpAthlete> selectByOldCoach(Integer oldCoachId) {
        return mapper.selectByOldCoach(oldCoachId);
    }

    @Override
    public List<AtsEmpAthlete> selectBysportId(AtsEmpAthlete atsEmpAthlete) {


        return mapper.selectBysportId(atsEmpAthlete);


    }

    @Override
    public List<AtsDataDic> findAllDataDic(Integer code) {
        String dcode = code.toString();//转换成String类型
        return dataDicMapper.selectDcode(dcode);
    }
}
